<template>
  <div id="Search">
    <van-nav-bar title="搜索" left-text="返回" right-text left-arrow @click-left="$router.go(-1)" />
    <van-search v-model.trim="value" @search="onSearch" show-action placeholder="请输入搜索关键词" />
    <div class="history" v-if="value==''">
      <h2>
        
        历史记录
        <span @click="removeHistory" style="float:right;margin-right:.5rem">
          <van-icon name="delete"  />
        </span>
      </h2>
      <ul>
        <li v-for="(item,i) in history" :key="i" v-html="item"></li>
      </ul>
    </div>

    <Recommend :goodslist="cateGroy" v-else />
  </div>
</template>

<script>
import storage from "@/utils/storage";
import Recommend from "../home/recommend";
export default {
  name: "Search",
  components: { Recommend },
  data() {
    return {
      goodslist: [],
      history: [],
      value: ""
    };
  },
  computed: {
    cateGroy() {
      let arr = this.goodslist;
      let val = this.value;
      if (val == "") {
        return [];
      }
      return arr.filter(item => {
        return item.name.indexOf(val) > -1;
      });
    }
  },
  methods: {
    getGoodsList() {
      this.$axios({
        url: "https://api.it120.cc/small4/shop/goods/list"
      }).then(res => {
        if (res.code == 0) {
          this.goodslist = res.data;
        }
      });
    },
    //获取历史记录表
    getHistory() {
      let data = storage.get("lativ", true);
      this.history = data == null ? [] : data;
    },
    //设置
    setHistory() {
      if (this.value.length == "") {
        return false;
      }

      this.history.unshift(this.value);
      if (this.history.length > 8) {
        this.history.pop();
      }
      storage.set("lativ", this.history, true);
    },
    //删除历史记录
    removeHistory() {
      storage.remove("lativ");
      this.getHistory();
    },
    onSearch() {
      this.setHistory();
      this.value = "";
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.getGoodsList();
    this.getHistory();
  }
};
</script>
<style scoped lang="scss">
/* @import url(); 引入css类 */
#Search {
  .history {
    width: 100%;
    h2 {
      font-size: 0.4rem;
      height: 0.8rem;
      line-height: 0.8rem;
      font-weight: bold;
      padding: 0.2rem;
      box-sizing: border-box;
    }
    ul {
      padding-top: 0.2rem;
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      li {
        width: 1.5rem;
        height: 0.5rem;
        line-height: 0.5rem;
        text-align: center;
        margin-left: 5%;
        background: rgb(221, 220, 220);
        border-radius: 0.2rem;
      }
    }
  }
}
</style>